package com.junyi;

import cn.hutool.core.img.Img;
import cn.hutool.core.io.FileUtil;
import org.junit.jupiter.api.Test;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;

/**
 * @time: 2022/1/21 16:16
 * @version: 1.0
 * @author: junyi Xu
 * @description:
 */
public class Compress {

    @Test
    public void test() {
        // method();
        method2();
    }


    /** 使用 JDK API */
    public void method() {
        try {
            File input = new File("G:\\pic\\source.jpg");
            BufferedImage image = ImageIO.read(input);


            Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
            ImageWriter writer = (ImageWriter) writers.next();

            File compressedImageFile = new File("target.jpg");
            OutputStream os = new FileOutputStream(compressedImageFile);
            ImageOutputStream ios = ImageIO.createImageOutputStream(os);
            writer.setOutput(ios);


            ImageWriteParam param = writer.getDefaultWriteParam();

            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(0.01f);

            writer.write(null, new IIOImage(image, null, null), param);

            os.close();
            ios.close();
            writer.dispose();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 使用 hutool 工具类
    public void method2() {
        Img.from(FileUtil.file("G:\\pic\\source.jpg"))
                .setQuality(0.5)//压缩比率
                .write(FileUtil.file("G:\\pic\\target.jpg"));
    }


}
